//
//  ViewController.m
//  07-二维码扫描
//
//  Created by HM on 16/10/18.
//  Copyright © 2016年 HM. All rights reserved.
//

#import "LWRichScanVc.h"
#import <AVFoundation/AVFoundation.h>
#import <SafariServices/SafariServices.h>
#import "HMPreView.h"

@interface LWRichScanVc ()<AVCaptureMetadataOutputObjectsDelegate>


//输入设备 摄像头
@property (nonatomic, strong) AVCaptureDeviceInput *input;

//输出设备  二维码算法生成的元数据
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
//会话  管理输入和输入设备
@property (nonatomic, strong) AVCaptureSession *session;
//预览视图layer
@property (nonatomic, strong) HMPreView *preview;

@end

@implementation LWRichScanVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //1.输入设备 摄像头
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //2.输出设备  二维码算法生成的元数据
    self.output = [[AVCaptureMetadataOutput alloc] init];
    //设置输出设备的代理  获取数据
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //3.会话  管理输入和输出设备
    self.session = [[AVCaptureSession alloc] init];
    //添加输入&输出设备
    [self.session addInput:self.input];
    [self.session addOutput:self.output];
    
    //输出设备的类型必须在输出设备添加到会话以后才能设置 AVMetadataObjectTypeQRCode二维码算法 iOS6内置
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    
    //4.预览视图
    HMPreView *preview = [[HMPreView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    preview.session = self.session;
    
    [self.view addSubview:preview];
    
    self.preview = preview;
    
    //开始会话
    [self.session startRunning];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate

/**
 *  已经生成元数据后调用
 *
 *  @param captureOutput   输出设备
 *  @param metadataObjects 转出的元数据
 *  @param connection      连接
 */
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    for (AVMetadataMachineReadableCodeObject *obj in metadataObjects) {
        
        
        //判断二维码数据是否为网页
        if ([obj.stringValue hasPrefix:@"http"]) {
            
            //创建内嵌的浏览器控制器
            SFSafariViewController *safariVc = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:obj.stringValue]];
            //进行modal展示
            [self presentViewController:safariVc animated:YES completion:nil];
            
            
        } else {
            
            NSLog(@"%@", [obj stringValue]);
            
        }
        
        
        //停止会话
        [self.session stopRunning];
        //移除预览视图
        [self.preview removeFromSuperview];
        return;
    }
}


@end
